import settingFile from '../setting.js'
/**
 * 对wx.request 的promise封装
 * @param {} config 
 */
function http(config){
  return new Promise((resolve,reject)=>{

    // {key:value} ==> url?key=value
    if(config.method.toLowerCase() == 'get'){
      if(config.data){
        var params = '';
        for(var key in config.data){
          params += '&'+key+'='+config.data[key];
        }
        params = params.substr(1);
      }
      config.url += '?'+params;
      delete config.data;
    }
    var options = {
      url: settingFile.host + '/api/v1' + config.url,
      data: config.data,
      method: config.method,
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res){
        resolve(res.data);
      },
      fail(err){
        reject(err);
      }
      
    }
    // 如果需要携带token需要带上
    if(config.token){
      try {
        var token = wx.getStorageSync('uu-token')
        if (token) {
          config.header.Authorization = token;
        }
      } catch (e) {
        // Do something when catch error
        console.error(e);
      }
    }
    if(config.header){
      options.header = Object.assign(options.header,config.header);
    }
    wx.request(options);
    
  })
}

export default http;